package com.zxk.util;

import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.*;
import com.sun.jna.platform.win32.WinUser;
import com.zxk.constant.JNAConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jws.soap.SOAPBinding;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取HWND列表
 */
public class HwndUtil {

    private static Logger LOG = LoggerFactory.getLogger(HwndUtil.class);

    public static List<HWND> hwnds = new ArrayList<>();

    public static String name = "";

    /**
     * 指定句柄名字，查找所有句柄
     *
     * @param hwndName
     * @return
     */
    public static List<HWND> getHwnds(String hwndName) {
        if (StringUtils.isEmpty(hwndName)) {
            LOG.error("查找hwnd失败,找到{}个", hwnds.size());
            return new ArrayList<>();
        }
        name = hwndName;
        //使用对象指针，回调，
        Pointer pointer = Pointer.createConstant(0);
        boolean emuWin = User32.INSTANCE.EnumWindows(new WndEnumProc(), pointer);
        if (!emuWin) {
            LOG.error("查找hwnd失败,找到{}个", hwnds.size());
            return new ArrayList<>();
        }
        LOG.info("成功找到hwnd,找到{}个", hwnds.size());
        return hwnds;
    }


}

/**
 * 重写WNDENUMPROC接口
 */
class WndEnumProc implements WinUser.WNDENUMPROC {

    @Override
    public boolean callback(HWND hWnd, Pointer data) {
        StringBuffer text = new StringBuffer(50);
        char[] lpString = new char[100];
        // 得到句柄窗口的名字
        User32.INSTANCE.GetWindowText(hWnd, lpString, text.capacity() + 1);
        if (lpString.length != 0) {
            String str = String.valueOf(lpString);
            if (str.contains(HwndUtil.name)) {
                HwndUtil.hwnds.add(hWnd);
            }
        }
        return true;
    }
}



